package nio.exercise;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Desc:   使用 通道 读取大文件
 * @author: cww
 * @DateTime: 2020-03-29 19:00
 */

public class ReadBigFileByChannel {
    private static final String fileSrc = "src/maindemo/java/java_thinking/unit_18_IO/exercise/LogFile.txt";
    public static void main(String[] args) throws Exception {
        splitFile(fileSrc, 10240);
    }

    /**
     * 使用通道分割文件
     * @param fileName  目标分割文件
     * @param bytePerFile   分割后每个文件的大小，单位 Byte
     */
    public static void splitFile(String fileName, int bytePerFile) throws IOException {
        RandomAccessFile file = new RandomAccessFile(fileName, "rw");
        FileChannel channel = file.getChannel();
        RandomAccessFile fileOut = new RandomAccessFile("src/maindemo/java/nio/exercise/split/i.txt","rw");
        ByteBuffer buf = ByteBuffer.allocate(bytePerFile);
        int flag = channel.read(buf);
        while(true) {
            if(flag == bytePerFile) {
                System.out.println("Read 读取" + bytePerFile);
                buf.flip();
                channel = fileOut.getChannel();
                while(buf.hasRemaining()) {
                    channel.write(buf);
                }
                break;
            }
        }
        System.out.println("write complete!");

    }
}
